<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Col,
  Descriptions,
  DescriptionsItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

import { getCapabilityDefinitions } from '#/api/resource-center';

import CapabilityDefinitionEditor from './CapabilityDefinitionEditor.vue';

// 响应式数据
const loading = ref(false);
const capabilityList = ref([]);
const currentCapability = ref(null);
const detailModalVisible = ref(false);
const editorModalVisible = ref(false);

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  status: '',
});

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 表格列定义
const columns = [
  {
    title: '能力名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '能力代码',
    dataIndex: 'code',
    key: 'code',
    width: 120,
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
  },
  {
    title: '版本',
    dataIndex: 'version',
    key: 'version',
    width: 80,
  },
  {
    title: '标签',
    dataIndex: 'tags',
    key: 'tags',
    width: 200,
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true,
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
  },
];

// 参数表格列
const parameterColumns = [
  {
    title: '参数名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '必填',
    dataIndex: 'required',
    key: 'required',
  },
  {
    title: '默认值',
    dataIndex: 'defaultValue',
    key: 'defaultValue',
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
  },
];

// 返回值表格列
const returnColumns = [
  {
    title: '返回值名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
  },
];

// 约束条件表格列
const constraintColumns = [
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '条件',
    dataIndex: 'condition',
    key: 'condition',
  },
  {
    title: '消息',
    dataIndex: 'message',
    key: 'message',
  },
];

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap = {
    active: 'green',
    inactive: 'orange',
    deprecated: 'red',
  };
  return colorMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    active: '启用',
    inactive: '禁用',
    deprecated: '废弃',
  };
  return textMap[status] || status;
};

// 获取分类颜色
const getCategoryColor = (category: string) => {
  const colorMap = {
    business: 'blue',
    communication: 'green',
    analytics: 'purple',
    security: 'red',
  };
  return colorMap[category] || 'default';
};

// 获取分类文本
const getCategoryText = (category: string) => {
  const textMap = {
    business: '业务能力',
    communication: '通信能力',
    analytics: '分析能力',
    security: '安全能力',
  };
  return textMap[category] || category;
};

// 格式化时间
const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleString();
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...searchForm,
    };

    const result = await getCapabilityDefinitions(params);
    capabilityList.value = result.list;
    pagination.total = result.total;
  } catch (error) {
    console.error('加载能力定义失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

// 刷新数据
const refreshData = () => {
  loadData();
};

// 查看详情
const viewDetail = (record: any) => {
  currentCapability.value = record;
  detailModalVisible.value = true;
};

// 编辑定义
const editDefinition = (record: any) => {
  currentCapability.value = record;
  editorModalVisible.value = true;
};

// 测试能力
const testCapability = (record: any) => {
  message.info(`测试能力: ${record.name}`);
  // TODO: 实现能力测试功能TODOTODO
};

// 删除定义
const deleteDefinition = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除能力定义 "${record.name}" 吗？`,
    onOk: async () => {
      try {
        // TODO: 实现删除API调用
        message.success('删除成功');
        loadData();
      } catch {
        message.error('删除失败');
      }
    },
  });
};

// 新建能力定义
const openCreateModal = () => {
  currentCapability.value = null;
  editorModalVisible.value = true;
};

// 编辑器成功回调
const onEditorSuccess = () => {
  editorModalVisible.value = false;
  loadData();
  message.success('操作成功');
};

// 初始化
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="capability-definition-manager">
    <div class="manager-header">
      <h2>能力定义管理</h2>
      <div class="header-actions">
        <Button type="primary" @click="openCreateModal">
          <IconifyIcon icon="ant-design:plus-outlined" />
          新建能力定义
        </Button>
        <Button @click="refreshData">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新
        </Button>
      </div>
    </div>

    <!-- 搜索和过滤 -->
    <div class="search-section">
      <Row :gutter="16">
        <Col :span="6">
          <Input
            v-model:value="searchForm.name"
            placeholder="搜索能力名称"
            allow-clear
            @change="handleSearch"
          />
        </Col>
        <Col :span="4">
          <Select
            v-model:value="searchForm.category"
            placeholder="选择分类"
            allow-clear
            @change="handleSearch"
          >
            <SelectOption value="business">业务能力</SelectOption>
            <SelectOption value="communication">通信能力</SelectOption>
            <SelectOption value="analytics">分析能力</SelectOption>
            <SelectOption value="security">安全能力</SelectOption>
          </Select>
        </Col>
        <Col :span="4">
          <Select
            v-model:value="searchForm.status"
            placeholder="选择状态"
            allow-clear
            @change="handleSearch"
          >
            <SelectOption value="active">启用</SelectOption>
            <SelectOption value="inactive">禁用</SelectOption>
            <SelectOption value="deprecated">废弃</SelectOption>
          </Select>
        </Col>
        <Col :span="4">
          <Button type="primary" @click="handleSearch">
            <IconifyIcon icon="ant-design:search-outlined" />
            搜索
          </Button>
        </Col>
      </Row>
    </div>

    <!-- 能力定义列表 -->
    <div class="capability-list">
      <Table
        :columns="columns"
        :data-source="capabilityList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>

          <template v-else-if="column.key === 'category'">
            <Tag :color="getCategoryColor(record.category)">
              {{ getCategoryText(record.category) }}
            </Tag>
          </template>

          <template v-else-if="column.key === 'tags'">
            <div class="tags-container">
              <Tag v-for="tag in record.tags" :key="tag" size="small">
                {{ tag }}
              </Tag>
            </div>
          </template>

          <template v-else-if="column.key === 'actions'">
            <Space>
              <Button type="link" size="small" @click="viewDetail(record)">
                <IconifyIcon icon="ant-design:eye-outlined" />
                查看
              </Button>
              <Button type="link" size="small" @click="editDefinition(record)">
                <IconifyIcon icon="ant-design:edit-outlined" />
                编辑
              </Button>
              <Button type="link" size="small" @click="testCapability(record)">
                <IconifyIcon icon="ant-design:experiment-outlined" />
                测试
              </Button>
              <Button
                type="link"
                size="small"
                danger
                @click="deleteDefinition(record)"
              >
                <IconifyIcon icon="ant-design:delete-outlined" />
                删除
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </div>

    <!-- 能力定义详情模态框 -->
    <Modal
      v-model:visible="detailModalVisible"
      title="能力定义详情"
      width="800px"
      :footer="null"
      :destroy-on-close="true"
    >
      <div v-if="currentCapability" class="capability-detail">
        <Descriptions :column="2" bordered>
          <DescriptionsItem label="能力名称">
            {{ currentCapability.name }}
          </DescriptionsItem>
          <DescriptionsItem label="能力代码">
            {{ currentCapability.code }}
          </DescriptionsItem>
          <DescriptionsItem label="分类">
            <Tag :color="getCategoryColor(currentCapability.category)">
              {{ getCategoryText(currentCapability.category) }}
            </Tag>
          </DescriptionsItem>
          <DescriptionsItem label="状态">
            <Tag :color="getStatusColor(currentCapability.status)">
              {{ getStatusText(currentCapability.status) }}
            </Tag>
          </DescriptionsItem>
          <DescriptionsItem label="版本">
            {{ currentCapability.version }}
          </DescriptionsItem>
          <DescriptionsItem label="创建时间">
            {{ formatTime(currentCapability.createTime) }}
          </DescriptionsItem>
          <DescriptionsItem label="描述" :span="2">
            {{ currentCapability.description }}
          </DescriptionsItem>
        </Descriptions>

        <!-- 参数定义 -->
        <div class="section">
          <h3>参数定义</h3>
          <Table
            :columns="parameterColumns"
            :data-source="currentCapability.parameters"
            :pagination="false"
            size="small"
          />
        </div>

        <!-- 返回值定义 -->
        <div class="section">
          <h3>返回值定义</h3>
          <Table
            :columns="returnColumns"
            :data-source="currentCapability.returns"
            :pagination="false"
            size="small"
          />
        </div>

        <!-- 约束条件 -->
        <div class="section">
          <h3>约束条件</h3>
          <Table
            :columns="constraintColumns"
            :data-source="currentCapability.constraints"
            :pagination="false"
            size="small"
          />
        </div>

        <!-- 依赖关系 -->
        <div class="section">
          <h3>依赖关系</h3>
          <div v-if="currentCapability.dependencies.length > 0">
            <Tag
              v-for="dep in currentCapability.dependencies"
              :key="dep"
              color="blue"
            >
              {{ dep }}
            </Tag>
          </div>
          <div v-else class="empty-text">无依赖关系</div>
        </div>

        <!-- 文档 -->
        <div class="section">
          <h3>文档</h3>
          <div class="documentation">
            {{ currentCapability.documentation || '暂无文档' }}
          </div>
        </div>
      </div>
    </Modal>

    <!-- 能力定义编辑模态框 -->
    <CapabilityDefinitionEditor
      v-model:visible="editorModalVisible"
      :capability="currentCapability"
      @success="onEditorSuccess"
    />
  </div>
</template>

<style lang="less" scoped>
.capability-definition-manager {
  .manager-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h2 {
      margin: 0;
      color: #262626;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .search-section {
    margin-bottom: 20px;
    padding: 16px;
    background-color: #fafafa;
    border-radius: 6px;
  }

  .capability-list {
    .tags-container {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
    }
  }

  .capability-detail {
    .section {
      margin-top: 24px;

      h3 {
        margin-bottom: 12px;
        color: #262626;
        font-size: 16px;
        font-weight: 500;
      }

      .empty-text {
        color: #8c8c8c;
        text-align: center;
        padding: 20px;
      }

      .documentation {
        background-color: #f5f5f5;
        padding: 12px;
        border-radius: 4px;
        color: #595959;
        line-height: 1.6;
      }
    }
  }
}
</style>
